﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using Microsoft.Reporting.WinForms;
using System.Linq.Expressions;
using Billing.DataObjects;
namespace Billing.Win
{
    public partial class InvoicesForm : Billing.WindowsBase.FormBase
    {
        public InvoicesForm()
        {
            InitializeComponent();
        }

        private void grdInvoices_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            e.Layout.Override.ActiveRowAppearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(251)))), ((int)(((byte)(230)))), ((int)(((byte)(148)))));
            e.Layout.Override.ActiveRowAppearance.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(238)))), ((int)(((byte)(149)))), ((int)(((byte)(21)))));
            e.Layout.Override.ActiveRowAppearance.BackGradientStyle = Infragistics.Win.GradientStyle.Vertical;
            e.Layout.Override.ActiveRowAppearance.ForeColor = System.Drawing.Color.DarkBlue;
            e.Layout.Override.CellClickAction = Infragistics.Win.UltraWinGrid.CellClickAction.RowSelect;
        }
        Billing.DataObjects.BillingDataContext dc = new Billing.DataObjects.BillingDataContext();
        System.Linq.IQueryable<Billing.DataObjects.InvoiceView> Invoices = null;

        private void InvoicesForm_Load(object sender, EventArgs e)
        {
            this.chkDate.Checked = true;
            this.chkInvoice.Checked = true;
            this.chkAmount.Checked = true;
            this.btnPrint.Enabled = false;
            this.cmbInvoiceTypes.DataSource = this.dc.InvoiceTypes;
            this.cmbInvoiceTypes.Value = 1;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            Billing.Reports.ReportManager frm = new Billing.Reports.ReportManager();

            this.SB.Panels["Status"].Text = String.Empty;
            this.btnRefresh.Enabled = false;
            this.btnPrint.Enabled = false;
            this.btnCancel.Enabled = true;
            this.btnClose.Enabled = false;

            highestPercentageReached = 0;
            BW.RunWorkerAsync(frm);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.btnPrint.Enabled = false;

            Invoices = from i in dc.InvoiceViews
                       where
                       ((i.InvoiceKey >= (int)this.numInvoiceFrom.Value &&
                       i.InvoiceKey <= (int)this.numInvoiceTo.Value)
                       || this.chkInvoice.Checked == true)
                       &&
                       ((i.DocumentDate >= (DateTime)this.dtFrom.Value &&
                       i.DocumentDate <= (DateTime)this.dtTo.Value)
                       || this.chkDate.Checked == true)
                        &&
                       ((i.Amount >= Convert.ToDecimal(this.numAmountFrom.Value) &&
                       i.Amount <= Convert.ToDecimal(this.numAmountTo.Value))
                       || this.chkAmount.Checked == true)
                       &&
                       ((this.chkNotPrinted.Checked == true && i.InvoiceStatusID < 4)
                       || this.chkNotPrinted.Checked == false)
                       &&
                       ( i.InvoiceTypeID ==(Int16) this.cmbInvoiceTypes.Value)
                       &&
                       (this.txtIdentificationNumber.Text.Length == 0 ||
                       (this.txtIdentificationNumber.Text.Length > 0 && i.ClientIdentificationNumber == this.txtIdentificationNumber.Text))
                       &&
                       ((int)this.numClientID.Value == 0 || ((int)this.numClientID.Value != 0 && (int)this.numClientID.Value == i.ClientID))
                       orderby i.InvoiceKey
                       select i;

            this.invoiceBindingSource.DataSource = Invoices;
            if (Invoices.Count() > 0)
                this.btnPrint.Enabled = true;
        }


        private int highestPercentageReached = 0;

        private void BW_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            Billing.Reports.ReportManager RM = (Billing.Reports.ReportManager)e.Argument;
            long result = 0;

            foreach (var item in Invoices)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                }
                else
                {
                    List<ReportParameter> rp = new List<ReportParameter>();
                    rp.Add(new ReportParameter("invoiceID", item.ID.ToString()));
                    if (item.InvoiceTypeID == 1)
                    {
                        RM.LoadReport(@"/BillingReports/Invoice", rp);
                        RM.LoadReport(@"/BillingReports/InvoiceDetails", rp);
                        RM.LoadReport(@"/BillingReports/Invoice", rp);
                    }
                    else if (item.InvoiceTypeID == 2)
                    {
                        RM.LoadReport(@"/BillingReports/InvoiceSimple", rp);
                        RM.LoadReport(@"/BillingReports/InvoiceSimpleDetails", rp);
                        RM.LoadReport(@"/BillingReports/InvoiceSimple", rp);
                    }
                    dc.InvoiceCommitPrint(item.ID);
                }

                result++;
                int percentComplete = (int)((float)result / (float)Invoices.Count() * 100);
                if (percentComplete > highestPercentageReached)
                {
                    highestPercentageReached = percentComplete;
                    worker.ReportProgress(percentComplete);
                }
            }
            e.Result = result;
        }

        private void BW_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.SB.Panels["ProgressBar"].ProgressBarInfo.Value = e.ProgressPercentage;
        }

        private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
                this.SB.Panels["Status"].Text = "ბეჭდვა გაუქმებულია.";
            }
            else
            {
                this.SB.Panels["Status"].Text = "დაბეჭდილია " + e.Result.ToString() + " ანგარიშფაქტურა.";
            }

            btnRefresh.Enabled = true;
            btnCancel.Enabled = false;
            this.btnClose.Enabled = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.BW.CancelAsync();
            this.btnCancel.Enabled = false;
        }

        private void chkDate_CheckedChanged(object sender, EventArgs e)
        {
            this.dtFrom.Enabled = !this.chkDate.Checked;
            this.dtTo.Enabled = !this.chkDate.Checked;
        }

        private void chkInvoice_CheckedChanged(object sender, EventArgs e)
        {
            this.numInvoiceFrom.Enabled = !this.chkInvoice.Checked;
            this.numInvoiceTo.Enabled = !this.chkInvoice.Checked;
        }

        private void chkAmount_CheckedChanged(object sender, EventArgs e)
        {
            this.numAmountFrom.Enabled = !this.chkAmount.Checked;
            this.numAmountTo.Enabled = !this.chkAmount.Checked;

        }

        private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            if (this.grdInvoices.Selected.Rows.Count == 0)
                return;

            switch (e.Tool.Key.ToLower())
            {
                case "mnuinvoice":
                    {
                        Billing.Reports.ReportForm frm = new Billing.Reports.ReportForm();
                        frm.ProcessingMode = ProcessingMode.Remote;
                        frm.PrintPreview = true;
                        frm.HideParameters = true;
                        List<ReportParameter> rp = new List<ReportParameter>();
                        rp.Add(new ReportParameter("invoiceID", this.grdInvoices.Selected.Rows[0].Cells["ID"].Value.ToString()));
                        frm.LoadReport(@"/BillingReports/Invoice", ProcessingMode.Remote, rp);
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    }
                case "mnuinvoicedetaile":
                    {
                        Billing.Reports.ReportForm frm = new Billing.Reports.ReportForm();
                        frm.ProcessingMode = ProcessingMode.Remote;
                        frm.PrintPreview = true;
                        frm.HideParameters = true;
                        List<ReportParameter> rp = new List<ReportParameter>();
                        rp.Add(new ReportParameter("invoiceID", this.grdInvoices.Selected.Rows[0].Cells["ID"].Value.ToString()));
                        frm.LoadReport(@"/BillingReports/InvoiceDetails", ProcessingMode.Remote, rp);
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    }
                case "simplifyinvoice":
                    {
                        Billing.Reports.ReportForm frm = new Billing.Reports.ReportForm();
                        frm.ProcessingMode = ProcessingMode.Remote;
                        frm.PrintPreview = true;
                        frm.HideParameters = true;
                        List<ReportParameter> rp = new List<ReportParameter>();
                        rp.Add(new ReportParameter("invoiceID", this.grdInvoices.Selected.Rows[0].Cells["ID"].Value.ToString()));
                        frm.LoadReport(@"/BillingReports/InvoiceSimple", ProcessingMode.Remote, rp);
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    }
                case "simplifyinvoicedetaile":
                    {
                        Billing.Reports.ReportForm frm = new Billing.Reports.ReportForm();
                        frm.ProcessingMode = ProcessingMode.Remote;
                        frm.PrintPreview = true;
                        frm.HideParameters = true;
                        List<ReportParameter> rp = new List<ReportParameter>();
                        rp.Add(new ReportParameter("invoiceID", this.grdInvoices.Selected.Rows[0].Cells["ID"].Value.ToString()));
                        frm.LoadReport(@"/BillingReports/InvoiceSimpleDetails", ProcessingMode.Remote, rp);
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    }
                default:
                    break;
            }
        }

        private void grdInvoices_AfterSelectChange(object sender, Infragistics.Win.UltraWinGrid.AfterSelectChangeEventArgs e)
        {
            if (this.grdInvoices.Selected.Rows.Count > 0)
            {
                InvoiceView row = (InvoiceView)this.grdInvoices.Selected.Rows[0].ListObject;
                if (row.InvoiceTypeID == 1)
                {
                    this.tb.Tools["mnuinvoice"].SharedProps.Visible = true;
                    this.tb.Tools["mnuinvoicedetaile"].SharedProps.Visible = true;
                }
                else
                {
                    this.tb.Tools["mnuinvoice"].SharedProps.Visible = false;
                    this.tb.Tools["mnuinvoicedetaile"].SharedProps.Visible = false;
                }
                if (row.InvoiceTypeID == 2)
                {
                    this.tb.Tools["simplifyinvoice"].SharedProps.Visible = true;
                    this.tb.Tools["simplifyinvoiceDetaile"].SharedProps.Visible = true;
                }
                else
                {
                    this.tb.Tools["simplifyinvoice"].SharedProps.Visible = false;
                    this.tb.Tools["simplifyinvoiceDetaile"].SharedProps.Visible = false;
                }

            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            InvoiceForm frm = new InvoiceForm(Billing.WindowsBase.eOpenMode.New);
            frm.ShowDialog();
        }

        private void cmbInvoiceTypes_ValueChanged(object sender, EventArgs e)
        {
            if ((Int16)this.cmbInvoiceTypes.Value == 1)
                this.btnAdd.Enabled = true;
            else
            {
                this.btnAdd.Enabled = false;
            }
        }





    }
}
